package com.lenovo.smarttraffic.ui.activity.stage8;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.SpotInfoBean;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TravelHelperActivity extends BaseActivity {

    public static List<SpotInfoBean.ROWSDETAILBean> spotList = new ArrayList<>();
    public static List<Map<String, Object>> cartList = new ArrayList<>();
    public static List<Integer> countList = new ArrayList<>();

    private Toolbar mToolbar;
    private TextView mToolbarTitle;
    private TextView mManagerTv;

    private RecyclerView mRvView;

    private LinearLayout mInfoParent;
    private ImageView mPic;
    private TextView mInfoTv;
    private LinearLayout mIndicateParent;
    private TextView mTelTv;

    private LinearLayout mCartParent;
    private CheckedTextView mTv1;
    private CheckedTextView mTv2;
    private TextView mMoreTv;
    private ListView mListView;
    private TextView mMoneyTv;
    private Button mPayBtn;
    private TextView mClearTv;

    private LinearLayout mQrParent;
    private TextView mQrInfo;
    private ImageView mQrImg;


    public Drawable drawable;
    public int pos = 0;

    public static String date = "";

    public CartAdapter cartAdapter;

    private Handler handler = new Handler();

    @Override
    protected int getLayout() {
        return R.layout.activity_travel_helper;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();

        mToolbar.setNavigationOnClickListener(v -> {
            if (mInfoParent.getVisibility() == View.VISIBLE || mCartParent.getVisibility() == View.VISIBLE) {
                showView(1);
            } else if (mQrParent.getVisibility() == View.VISIBLE) {
                showView(3);
            } else finish();
        });

        for (int i = 0; i < 5; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setPadding(10, 20, 10, 20);
            imageView.setImageResource(R.drawable.indicate_large);
            imageView.setTag(i);
            mIndicateParent.addView(imageView);
        }

        //获取旅游信息
        HttpUtils.post("GetSpotInfo.do", new HttpUtils().add("UserName", MainActivity.userName),
                response -> {
                    spotList = new Gson().fromJson(response.toString(), SpotInfoBean.class).getROWS_DETAIL();

                    mRvView.setAdapter(new SpotAdapter(this));
                });
    }

    public void showView(int which) {
        if (which == 1) {
            mToolbarTitle.setText("旅行助手");
            mInfoParent.setVisibility(View.GONE);
            mRvView.setVisibility(View.VISIBLE);
            mManagerTv.setVisibility(View.GONE);

        } else if (which == 2) {
            mToolbarTitle.setText("详细信息");
            mRvView.setVisibility(View.GONE);
            mCartParent.setVisibility(View.GONE);
            mManagerTv.setVisibility(View.GONE);
            mInfoParent.setVisibility(View.VISIBLE);

            if (drawable != null) {
                mPic.setImageDrawable(drawable);
            }

            SpotInfoBean.ROWSDETAILBean bean = spotList.get(pos);
            mInfoTv.setText("景点介绍\n" + bean.getInfo());
            for (int i = 0; i < 5; i++) {
                ImageView imageView = mIndicateParent.findViewWithTag(i);
                if (i <= bean.getRating()) {
                    imageView.setImageResource(R.drawable.indicate_selected_blue_large);
                } else {
                    imageView.setImageResource(R.drawable.indicate_large);
                }
            }
            String tel = bean.getTel();
            mTelTv.setText("联系电话\n" + tel);
            mTelTv.setOnClickListener(v -> {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + tel));
                    startActivity(intent);
                } catch (Exception e) {
                    ToastUtils.showToast(this, e.getMessage());
                }
            });
        } else if (which == 3) {
            mToolbarTitle.setText("购物车");
            mRvView.setVisibility(View.GONE);
            mInfoParent.setVisibility(View.GONE);
            mManagerTv.setVisibility(View.VISIBLE);
            mCartParent.setVisibility(View.VISIBLE);

            mManagerTv.setOnClickListener(v -> {
                cartAdapter.showDel = !cartAdapter.showDel;
                cartAdapter.notifyDataSetChanged();
            });

            Calendar calendar = Calendar.getInstance();
            String month = calendar.get(Calendar.MONTH) + "";
            String day = calendar.get(Calendar.DAY_OF_MONTH) + "";

            if (month.length() < 2) {
                month = "0" + month;
            }
            if (day.length() < 2) {
                day = "0" + day;
            }
            mTv1.setText("今天" + month + "/" + day + "\n预定");

            calendar.add(Calendar.DAY_OF_MONTH, 1);
            String day2 = calendar.get(Calendar.DAY_OF_MONTH) + "";
            if (day2.length() < 2) {
                day2 = "0" + day2;
            }
            mTv2.setText("明天" + month + "/" + day2 + "\n预定");

            mMoreTv.setOnClickListener(v -> {
                Calendar ca = Calendar.getInstance();
                int mYear = ca.get(Calendar.YEAR);
                int mMonth = ca.get(Calendar.MONTH);
                int mDay = ca.get(Calendar.DAY_OF_MONTH);
                //Init date picker
                DatePickerDialog dialog = new DatePickerDialog(this, onDateSetListener, mYear, mMonth, mDay);
                dialog.setButton(DatePickerDialog.BUTTON_POSITIVE, getText(android.R.string.ok), (i1, i2) -> {
                    DatePicker mDatePicker = dialog.getDatePicker();
                    // Clearing focus forces the dialog to commit any pending
                    // changes, e.g. typed text in a NumberPicker.
                    mDatePicker.clearFocus();
                    onDateSetListener.onDateSet(mDatePicker, mDatePicker.getYear(),
                            mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
                });
                dialog.show();
            });

            if (cartAdapter == null) {
                cartAdapter = new CartAdapter(this);
                mListView.setAdapter(cartAdapter);
            } else {
                cartAdapter.showDel = false;
                cartAdapter.notifyDataSetChanged();
            }

            calcMoney();

            mPayBtn.setOnClickListener(v -> {
                if (cartList.isEmpty()) {
                    ToastUtils.showToast(this, "购物车还没有商品");
                } else {
                    showView(4);
                }
            });

            mClearTv.setOnClickListener(v -> {
                cartList.clear();
                countList.clear();
                cartAdapter.notifyDataSetChanged();
                calcMoney();
            });
        } else {
            mToolbarTitle.setText("支付界面");
            mCartParent.setVisibility(View.GONE);
            mQrInfo.setVisibility(View.GONE);
            mQrParent.setVisibility(View.VISIBLE);
            mManagerTv.setVisibility(View.GONE);

            mQrImg.setOnLongClickListener(v -> {
                mQrInfo.setVisibility(mQrInfo.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                return true;
            });
            runnable.run();
        }
    }

    int money = 0;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            StringBuilder place = new StringBuilder(cartList.get(0).get("name") + ",");
            for (int i = 1; i < cartList.size(); i++) {
                place.append(",").append(cartList.get(i).get("name"));
            }

            String qrInfo = "付款项目：" + place + " 付款金额：" + money;
            mQrInfo.setText(qrInfo);
            mQrImg.setImageBitmap(Utils.createQRCodeImage(qrInfo + System.currentTimeMillis(), 200, 200));

            handler.postDelayed(runnable, 5000);
        }
    };

    public void calcMoney() {
        money = 0;
        for (int i = 0; i < cartList.size(); i++) {
            money += (int) cartList.get(i).get("money") * countList.get(i);
        }
        mMoneyTv.setText("总金额：" + money + "元");
    }

    private DatePickerDialog.OnDateSetListener onDateSetListener = (view, year, monthOfYear, dayOfMonth) -> {
        String mMonth = (monthOfYear + 1) + "/";
        String mDay = dayOfMonth + "";

        if (mMonth.length() < 3) {
            mMonth = "0" + mMonth;
        }
        if (mDay.length() < 2) {
            mDay = "0" + mDay;
        }

        date = mMonth + mDay;
        mTv1.setText("今天" + date + "\n预定");

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, monthOfYear, dayOfMonth);
        calendar.add(Calendar.MONTH, 1);

        String month2 = calendar.get(Calendar.MONTH) + "";
        if (month2.length() < 3) {
            month2 = "0" + month2;
        }
        String day2 = calendar.get(Calendar.DAY_OF_MONTH) + "";
        if (day2.length() < 3) {
            day2 = "0" + day2;
        }
        mTv2.setText("明天" + month2 + day2 + "\n预定");
    };

    @Override
    public void onBackPressedSupport() {
        if (mInfoParent.getVisibility() == View.VISIBLE || mCartParent.getVisibility() == View.VISIBLE) {
            showView(1);
        } else if (mQrParent.getVisibility() == View.VISIBLE) {
            showView(3);
        } else super.onBackPressedSupport();
    }

    private void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mToolbarTitle = findViewById(R.id.toolbar_title);
        mManagerTv = findViewById(R.id.manager_tv);
        mRvView = findViewById(R.id.rvView);
        mInfoParent = findViewById(R.id.info_parent);
        mPic = findViewById(R.id.pic);
        mInfoTv = findViewById(R.id.info_tv);
        mIndicateParent = findViewById(R.id.indicate_parent);
        mTelTv = findViewById(R.id.tel_tv);
        mCartParent = findViewById(R.id.cart_parent);
        mTv1 = findViewById(R.id.tv1);
        mTv2 = findViewById(R.id.tv2);
        mMoreTv = findViewById(R.id.more_tv);
        mListView = findViewById(R.id.listView);
        mMoneyTv = findViewById(R.id.money_tv);
        mPayBtn = findViewById(R.id.pay_btn);
        mClearTv = findViewById(R.id.clear_tv);
        mQrParent = findViewById(R.id.qr_parent);
        mQrInfo = findViewById(R.id.qr_info);
        mQrImg = findViewById(R.id.qr_img);
    }
}

class CartAdapter extends BaseAdapter {
    TravelHelperActivity activity;

    List<Map<String, Object>> cartList = TravelHelperActivity.cartList;
    List<Integer> countList = TravelHelperActivity.countList;

    boolean showDel = false;

    public CartAdapter(TravelHelperActivity activity) {
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return cartList.size();
    }

    @Override
    public Object getItem(int position) {
        return cartList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_spot_buy, parent, false);
            holder.delete = convertView.findViewById(R.id.delete);
            holder.img = convertView.findViewById(R.id.img);
            holder.name = convertView.findViewById(R.id.name);
            holder.info = convertView.findViewById(R.id.info);
            holder.count = convertView.findViewById(R.id.count);
            holder.money = convertView.findViewById(R.id.money);
            holder.minus = convertView.findViewById(R.id.minus);
            holder.plus = convertView.findViewById(R.id.plus);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.delete.setVisibility(showDel ? View.VISIBLE : View.INVISIBLE);
        holder.delete.setOnClickListener(v -> {
            cartList.remove(position);
            countList.remove(position);
            notifyDataSetChanged();
            activity.calcMoney();
        });

        Map<String, Object> map = cartList.get(position);
        int count = countList.get(position);

        holder.img.setImageDrawable((Drawable) map.get("img"));
        holder.name.setText((String) map.get("name"));
        holder.info.setText((String) map.get("info"));
        holder.count.setText("" + count);

        holder.minus.setTextColor(Utils.getColor(parent.getContext(), count < 1 ? R.color.Grey : R.color.Black));
        holder.minus.setOnClickListener(v -> {
            int count2 = countList.get(position);
            if (count2 > 0) {
                countList.set(position, count2 - 1);
                notifyDataSetChanged();
                activity.calcMoney();
            }
        });
        holder.plus.setOnClickListener(v -> {
            countList.set(position, countList.get(position) + 1);
            notifyDataSetChanged();
            activity.calcMoney();
        });
        holder.money.setText(map.get("money") + " 元");

        return convertView;
    }

    static class ViewHolder {
        TextView delete;
        ImageView img;
        TextView name, info, minus, count, plus, money;
    }

}

class SpotAdapter extends RecyclerView.Adapter<SpotAdapter.ViewHolder> {

    private List<SpotInfoBean.ROWSDETAILBean> spotList = TravelHelperActivity.spotList;

    TravelHelperActivity activity;

    public SpotAdapter(TravelHelperActivity activity) {
        this.activity = activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_spot, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SpotInfoBean.ROWSDETAILBean bean = spotList.get(position);

        String picUrl = Constant.urlPrefix + bean.getImg();
        Glide.with(InitApp.getContext()).load(picUrl).placeholder(R.drawable.page_loading).error(R.drawable.ic_error_page).into(holder.pic);

        holder.place_tv.setText(bean.getName());
        holder.buy_btn.setOnClickListener(v -> {
            Map<String, Object> map = new HashMap<>();
            map.put("img", holder.pic.getDrawable());
            map.put("name", bean.getName());
            map.put("info", bean.getInfo());
            map.put("money", bean.getTicket());
            TravelHelperActivity.cartList.add(map);
            TravelHelperActivity.countList.add(1);

            activity.showView(3);
        });
        holder.itemView.setOnClickListener(v -> {
            activity.pos = holder.getAdapterPosition();
            activity.drawable = holder.pic.getDrawable();
            activity.showView(2);
        });

        holder.money_tv.setText("票价 ¥" + bean.getTicket());
    }

    @Override
    public int getItemCount() {
        return spotList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView pic;
        TextView place_tv;
        Button buy_btn;
        TextView money_tv;

        public ViewHolder(View itemView) {
            super(itemView);
            pic = itemView.findViewById(R.id.pic);
            place_tv = itemView.findViewById(R.id.place_tv);
            buy_btn = itemView.findViewById(R.id.buy_btn);
            money_tv = itemView.findViewById(R.id.money_tv);
        }
    }
}

